const express = require('express');
const app = express();
app.listen(3000, () => {
  console.log('服务器已开启')
});
//引入mysql
const mysql = require('mysql');


//创建mysql数据库的配置连接
let con = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  port: 3306,
  database: 'demo'
})
//连接
con.connect();

//接参
app.use(express.urlencoded({
  extended: false
}));

//注册
app.post('/register', (req, res) => {
  function fn1() {
    return new Promise((resolve, reject) => {
      //接参
      let {
        username,
        password
      } = req.body;
      console.log(req.body);
      con.query(`SELECT * FROM member WHERE username ='${username}'`, (err, result) => {
        if (err) {
          res.send({
            code: 500,
            mag: err
          });
          return
        }
        if (result.length > 0) {
          res.send({
            code: 400,
            msg: '用户名已存在'
          });
        }
        resolve({
          username,
          password
        })
      })
    })
  }
  async function fn2() {
    let {
      username,
      password
    } = await fn1();
    //不存在的话添加到数据库中
    con.query(`insert into member (username,password) values ("${username}","${password}")`, (err, result) => {
      if (err) {
        res.send({
          code: 500,
          mag: err
        });
        return
      }
      if (result.insertId > 0) {
        res.send({
          code: 200,
          msg: '注册成功'
        })
      } else {
        res.send({
          code: 400,
          msg: '请稍后再试'
        })
      }
    })
  }
  fn2()
})

//登录
app.post('/login', (req, res) => {
  //(1)、获取前端传递过来的参数
  let {
    username,
    password
  } = req.body;
  con.query(`SELECT * FROM member WHERE username ='${username}' and password = '${password}'`, (err, result) => {
    if (err) {
      res.send({
        code: 500,
        mag: err
      });
      return
    }
    if (result.length > 0) {
      res.send({
        code: 200,
        msg: '登录成功'
      })
    } else {
      res.send({
        code: 400,
        msg: '用户名或密码错误'
      })
    }
  })
})